package org.iqiyi.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author huqi 2021/10/22
 */
public class TreeUtil {
    /**
     * @param parentName 父级编号对应的字段名
     * @param idName 主键的字段名称
     * @param list 数据库查询出来的数据
     * */
    public static JSONArray createTreeJson(List<?> list,String parentName,String idName) throws Exception {
        JSONArray rootArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            Class resource = list.get(i).getClass();
            Object objectResource = list.get(i);
            // 解除私有化限制
            for (Field field : resource.getDeclaredFields()) {
                if (field.getName().equals(parentName)) {
                    field.setAccessible(true);
                    String parentIdField = field.get(objectResource).toString();
                    if (parentIdField.equals("0")) {
                        //创建子节点分支
                        JSONObject rootObj = createBranch(list, objectResource,parentName,idName);
                        rootArray.add(rootObj);
                    }
                }
            }
        }
        return rootArray;
    }

    public static JSONObject createBranch(List<?> list, Object currentNode, String parentName, String idName) throws Exception {
        JSONObject currentObj = (JSONObject) JSONObject.toJSON(currentNode);
        JSONArray childArray = new JSONArray();
        String parentIdField = null;
        String idField = null;
        for (int i = 0; i < list.size(); i++) {
            Class newNode = list.get(i).getClass();
            Class currentNodeClass = currentNode.getClass();
            for (Field field : newNode.getDeclaredFields()){
                if (field.getName().equals(parentName)) {
                    field.setAccessible(true);
                    // 反射获取值
                    parentIdField = field.get(list.get(i)).toString();
                }
            }
            for (Field field : currentNodeClass.getDeclaredFields()) {
                if (field.getName().equals(idName)) {
                    field.setAccessible(true);
                    // 反射获取值
                    idField = field.get(currentNode).toString();
                }
            }

            if (parentIdField != null && idField != null && parentIdField.equals(idField)) {
                JSONObject childObj = createBranch(list, list.get(i),parentName,idName);
                childArray.add(childObj);
            }
        }
        if (!childArray.isEmpty()) {
            currentObj.put("children", childArray);
        }
        return currentObj;
    }
}
